package com.aek.aekdroid;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;

import com.aek.aekdroid.data.IDbConstants;
import com.aek.aekdroid.data.MatchData;

public class CreateMatchActivity extends BaseActivity {

	private int matchId = -1;
	private ArrayAdapter<CharSequence> channelAdapter;
	private ArrayAdapter<CharSequence> tournamentAdapter;
	private TextView homeTeam;
	private TextView awayTeam;
	private TextView stadium;
	private TextView datetime;
	private TextView homeGoals;
	private TextView awayGoals;
	private Spinner channel;
	private Spinner tournament;

	private int id;
	public static final String TAG = "CreateMatchActivity";
	public static final String MATCH_ID = "MATCH_ID";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.create_match);
		initComponents();
		loadMatch();
		Button cancel = (Button) findViewById(R.id.create_match_cancel);
		Button ok = (Button) findViewById(R.id.create_match_ok);
		TextView title = (TextView) findViewById(R.id.create_match_title);
		title.setText(matchId == -1 ? R.string.create_match_createMatch : R.string.create_match_editMatch);
		ok.setText(matchId == -1 ? R.string.create_match_create : R.string.create_match_edit);
		cancel.setOnClickListener(new ClickListener());
		ok.setOnClickListener(new ClickListener());

	}

	private void initComponents() {
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			matchId = bundle.getInt(CreateMatchActivity.MATCH_ID, -1);
		}
		channelAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, IDbConstants.CHANNELS);
		channelAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		tournamentAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, IDbConstants.TOURNAMENTS);
		tournamentAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		homeTeam = (TextView) findViewById(R.id.create_match_homeTeam);
		awayTeam = (TextView) findViewById(R.id.create_match_awayTeam);
		stadium = (TextView) findViewById(R.id.create_match_stadium);
		datetime = (TextView) findViewById(R.id.create_match_datetime);
		channel = (Spinner) findViewById(R.id.create_match_channel);
		tournament = (Spinner) findViewById(R.id.create_match_tournament);
		homeGoals = (TextView) findViewById(R.id.create_match_homeGoals);
		awayGoals = (TextView) findViewById(R.id.create_match_awayGoals);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return false;
	}

	@Override
	public void onBackPressed() {
		if (matchId > 0) {
			Intent showMatchIntent = new Intent(this, ShowMatchActivity.class);
			showMatchIntent.putExtra(IDbConstants.MATCHES_C_ID, matchId);
			startActivity(showMatchIntent);
		} else {
			Intent scheduleActivity = new Intent(this, ScheduleActivity.class);
			startActivity(scheduleActivity);
		}
	}

	private void loadMatch() {
		MatchData m = new MatchData(this);
		channel.setAdapter(channelAdapter);
		tournament.setAdapter(tournamentAdapter);
		Cursor c = null;
		if (matchId > -1) {
			try {
				c = m.getMatch(matchId);
				// Get Form comps

				if (c.moveToFirst()) {
					id = c.getInt(c.getColumnIndex(IDbConstants.MATCHES_C_ID));
					homeTeam.setText(c.getString(c.getColumnIndex(IDbConstants.MATCHES_C_HOME_TEAM)));
					awayTeam.setText(c.getString(c.getColumnIndex(IDbConstants.MATCHES_C_AWAY_TEAM)));
					homeGoals.setText(c.getString(c.getColumnIndex(IDbConstants.MATCHES_C_HOME_GOALS)));
					awayGoals.setText(c.getString(c.getColumnIndex(IDbConstants.MATCHES_C_AWAY_GOALS)));
					stadium.setText(c.getString(c.getColumnIndex(IDbConstants.MATCHES_C_STADIUM)));
					long d = c.getLong(c.getColumnIndex(IDbConstants.MATCHES_C_DATETIME));

					datetime.setText(Helper.createDate(d));
					channel.setSelection(channelAdapter.getPosition(c.getString(c.getColumnIndex(IDbConstants.MATCHES_C_CHANNEL))));
					tournament
							.setSelection(tournamentAdapter.getPosition(c.getString(c.getColumnIndex(IDbConstants.MATCHES_C_TOURNAMENT))));
				}
			} finally {
				if (c != null) {
					c.close();
				}
			}
		}
	}

	public void save() {
		ContentValues values = new ContentValues();
		MatchData m = new MatchData(this);
		String date = datetime.getText().toString();
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
		long time;
		try {
			time = sdf.parse(date).getTime();
		} catch (ParseException e) {
			time = 0;
		}
		values.put(IDbConstants.MATCHES_C_DATETIME, time);
		values.put(IDbConstants.MATCHES_C_TOURNAMENT, tournament.getSelectedItem().toString());
		values.put(IDbConstants.MATCHES_C_HOME_TEAM, homeTeam.getText().toString());
		values.put(IDbConstants.MATCHES_C_AWAY_TEAM, awayTeam.getText().toString());
		values.put(IDbConstants.MATCHES_C_HOME_GOALS, homeGoals.getText().toString());
		values.put(IDbConstants.MATCHES_C_AWAY_GOALS, awayGoals.getText().toString());
		values.put(IDbConstants.MATCHES_C_STADIUM, stadium.getText().toString());
		values.put(IDbConstants.MATCHES_C_CHANNEL, channel.getSelectedItem().toString());

		m.update(values, id);
		finish();
	}

	public void submit() {
		String pass = aek.getPassword();
		String time = datetime.getText().toString();
		int tour = tournament.getSelectedItemPosition();
		String home = homeTeam.getText().toString();
		String away = awayTeam.getText().toString();
		String stad = stadium.getText().toString();
		String homeG = homeGoals.getText().toString().equals("") ? "0" : homeGoals.getText().toString();
		String awayG = awayGoals.getText().toString().equals("") ? "0" : awayGoals.getText().toString();
		int chan = channel.getSelectedItemPosition();

		String query = "&pass=" + pass + "&id=" + this.matchId + "&time=" + Uri.encode(time) + "&tour=" + tour + "&home="
				+ Uri.encode(home) + "&away=" + Uri.encode(away) + "&stad=" + Uri.encode(stad) + "&chan=" + chan + "&homeGoals=" + homeG
				+ "&awayGoals=" + awayG;

		String url = WebAekDroid.CREATE_URL + query;
		MyLog.d(TAG, "Submiting match " + url);
		Helper.adminFunction(this, url);
	}

	private long getTime(String datetime) {
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
		long time;
		try {
			return sdf.parse(datetime).getTime();
		} catch (ParseException e) {
			return 0;
		}
	}

	class ClickListener implements View.OnClickListener {

		@Override
		public void onClick(View v) {
			if (v.getId() == R.id.create_match_ok) {
				CreateMatchActivity.this.submit();
			} else if (v.getId() == R.id.create_match_cancel) {
				finish();
			}

		}

	}

}
